package com.cskaoyan.controller;

import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.model.MarketUser;
import com.cskaoyan.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author zoe ling
 * @Date 2024/6/12
 */
@RestController
@RequestMapping("wx/auth")
public class WxAuthController {
    @Autowired
    UserService userService;

    @PostMapping("login")
    public BaseRespVo login(@RequestBody Map<String,String> map){
        String username = map.get("username");
        String password = map.get("password");
        Subject subject = SecurityUtils.getSubject();
        subject.login(new UsernamePasswordToken(username, password));
        boolean authenticated = subject.isAuthenticated();
        System.out.println(subject);
        System.out.println(subject.getSession().getId());
        //登录成功
        if (authenticated) {
            // 在认证(登录)成功的情况下 可以获取用户信息 → realm中doGetAuthenticationInfo中的返回的simpleAuthenticationInfo中的第一个参数
            // 存的是user的id，那么取出来的也是user的id
            Integer userId = (Integer) subject.getPrincipal();
            MarketUser user = userService.findById(userId);

            HashMap<String, Object> data = new HashMap<>();
            // 返回SessionId → 小程序的其他请求就会携带这个SessionId过来
            data.put("token", subject.getSession().getId());
            HashMap<String, String> userInfo = new HashMap<>();
            userInfo.put("nickName", user.getNickname());
            userInfo.put("avatarUrl", user.getAvatar());
            data.put("userInfo", userInfo);
            return BaseRespVo.ok(data);
        }
        return BaseRespVo.ok("token");
        // MarketUser user=userService.findByName(username);
        // if (user!=null&&(user.getPassword()).equals(password)){
        //     //登录成功
        //     HashMap<String,Object> data=new HashMap<>();
        //     data.put("token",1234);
        //     HashMap<String,String> userInfo=new HashMap<>();
        //     userInfo.put("avatarUrl",user.getAvatar());
        //     userInfo.put("nickName",user.getNickname());
        //     data.put("userInfo",userInfo);
        //     return BaseRespVo.ok(data);
        // }
        //
        // return BaseRespVo.msg("登录失败");
    }

    @GetMapping("unAuthc")
    public BaseRespVo unAuthc() {
        return BaseRespVo.unAuthc();
    }
}
